package cn.tedu.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 封装生成token和验证token方法
 */
public class JWTUtil {
    /**
     * 生成token header.payload.signature
     */
    private static String SIGNATURE="token!Q2W#E$RW";


    public static void main(String[] args) {

        Map<String,String> map = new HashMap<>();
        map.put("username","jx");
        map.put("password","123456");
        String token = JWTUtil.getToken(map);
        JWTUtil.verify(token);
        Map<String, String> tokenInfo = JWTUtil.getTokenInfo(token);
        System.out.println(tokenInfo);

    }
    /**
     * 生成token
     * @param map
     * @return
     */
    public static String getToken(Map<String,String> map){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7); //默认7天过期
        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        //payload,用遍历避免多个键值对
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        //指定令牌过期时间,设置签名返回token
        String token = builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SIGNATURE));
        return token;
    }

    /**
     * 验证token合法性
     * @param token
     */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
    }

    public static Map<String,String> getTokenInfo(String token){
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGNATURE)).build().verify(token);
        Map<String, Claim> claims = verify.getClaims();
        Map<String,String> map = new HashMap<>();
        Set<Map.Entry<String, Claim>> entries = claims.entrySet();
        for (Map.Entry<String, Claim> entry : entries) {
            map.put(entry.getKey(),entry.getValue().asString());
        }
        return map;
    }


}
